// pages/cart/cart.js
import {getSetting,chooseAddress,openSetting,showToast} from "../../utils/asyncWx.js"

Page({
  data:{
    address:{},
    cart:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0
  },
  onShow(){
    // 获取缓存中的值
    const address=wx.getStorageSync("address")
    // console.log(address)
    const cart=wx.getStorageSync("cart")||[]
    this.setData({address})
    this.setCart(cart)
  },
  // 点击收货地址
  async handleChooseAdress(){
   try{
    const res1 =await getSetting()
    const scopeAddress=res1.authSetting["scope.address"]  
    if(scopeAddress===false){
      await openSetting()
    }
      let address=await chooseAddress()
      address.all=address.provinceName+address.cityName+address.countyName+address.detailInfo
      // console.log(res2)
      wx.setStorageSync("address", address);
        
   }catch(error){
    console.log(error)
   }
  },
  // 商品的选中
  handleChange(e){
    // console.log(e)
    const goods_id=e.currentTarget.dataset.id
    // console.log(goods_id)
    let {cart} =this.data
    let index=cart.findIndex(v=>v.goods_id===goods_id)
    cart[index].checked=!cart[index].checked
    this.setCart(cart)
  },
  // 封装
  setCart(cart){
    let allChecked=true
    let totalPrice=0
    let totalNum=0
      cart.forEach(v => {
        if(v.checked){
          totalPrice+=v.num*v.goods_price
          totalNum+=v.num
        }else{
          allChecked=false
        }
      })
        // 判断数组是否为空
        allChecked=cart.length!=0?allChecked:false
  
       this.setData({
        cart,
        allChecked,
        totalPrice,
        totalNum
       })
       wx.setStorageSync("cart", cart)
  },
  // 全选功能
  handleItemAllChecked(){
    let {cart,allChecked}=this.data
    allChecked=!allChecked
    cart.forEach(v=>v.checked=allChecked)
    this.setCart(cart)
  },
  hanleItemNumEdit(e){

    const {operation,id}=e.currentTarget.dataset
    // console.log(operation,id)
    let {cart} = this.data
    const index=cart.findIndex(v=>v.goods_id===id)
    if(cart[index].num===1&&operation===-1){
      wx.showModal({
        title: '提示',
        content: '您是否要删除',
        success :(res) =>{
          if (res.confirm) {
            cart.splice(index,1)
            this.setCart(cart)
          } else if (res.cancel) {
            cart[index].num=1
            this.setCart(cart)
          }
        }
      })
    }
    cart[index].num+=operation
    this.setCart(cart)
  },
  // 结算功能
  async handlePay(){
    const {address,totalNum} = this.data
    if(!address.userName){
      await showToast({title:"您还没有选择收货地址"})
      return
    }
    if(totalNum===0){
      await showToast({title:"您还没有选购商品"})
      return
    }
    wx.navigateTo({
      url: '/pages/pay/pay'
    })
      
  }
})

